package tools.action.controller {
	import engine.animation.Texture;

	import kiwi.action.Action;
	import kiwi.action.load.LoaderAction;
	import kiwi.debug.Log;
	import kiwi.event.ActionEvent;
	import kiwi.loader.SWFLoader;

	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;

	/**
	 * 读取一个外部的素材文件
	 * @author zhangming.luo
	 */
	public class LoadTextureAction extends Action {
		private var url : String;
		private var loadAction : LoaderAction;
		private var texture : Texture = new Texture();
		public var animationDic : Dictionary = new Dictionary();
		private var loader : SWFLoader;

		public function LoadTextureAction(url : String) {
			this.url = url;
		}

		override public function execute() : void {
			super.execute();
			// 需要加载
			loadAction = new LoaderAction(loader = new SWFLoader(url));
			loadAction.addEventListener(ActionEvent.ACTION_COMPLETE, handleComplete);
			loadAction.addEventListener(ActionEvent.ACTION_FAULT, handleFault);
			loadAction.execute();
		}

		private function clearAction(action : Action) : void {
			action.removeEventListener(ActionEvent.ACTION_COMPLETE, handleComplete);
			action.removeEventListener(ActionEvent.ACTION_FAULT, handleFault);
		}

		private function handleFault(event : ActionEvent) : void {
			clearAction(Action(event.currentTarget));
			fault();
		}

		private function handleComplete(event : ActionEvent) : void {
			clearAction(Action(event.currentTarget));
			var prefix : String = "";
			var r : Array = url.match(/.*\/asset(\/.*\/[^.]*).ani/);
			if (r && r.length > 1) {
				prefix += String(r[1]).replace(/\//g, "_");
			} else {
				Log.error("Texture的前缀无法获取" + url);
			}
			var textureClz : Class = Class(loader.getDefinitionByName("TEXTURE" + prefix));
			var textureConfClz : Class = Class(loader.getDefinitionByName("TEXTURE_CONF" + prefix));
			var tmp : Object = new textureClz;
			texture.bitmapData = BitmapData(tmp is Bitmap ? Bitmap(tmp).bitmapData : tmp);
			texture.setConfig(new XML(ByteArray(new textureConfClz)));
			texture.getAnimationDic(animationDic);
			texture.$init = true;
			result();
		}
	}
}
